package com.wyl.studyredis.business.controller;


import cn.hutool.core.util.StrUtil;
import com.wyl.studyredis.business.dto.StudentAddDto;
import com.wyl.studyredis.business.dto.StudentUpdateDto;
import com.wyl.studyredis.business.entity.Student;
import com.wyl.studyredis.business.service.IStudentService;
import com.wyl.studyredis.business.vo.StudentVo;
import com.wyl.studyredis.framework.ResponseVo;
import com.wyl.studyredis.framework.util._BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wyl
 * @since 2022-02-11
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @PostMapping("/getById")
    public ResponseVo<StudentVo> getById(@RequestParam("id") String id){
        if (StrUtil.isBlank(id)) {
            return ResponseVo.fail("主键不能为空");
        }
        try {
            StudentVo studentVo = studentService.getStudentVoByIdInCache(id, true);
            return ResponseVo.success(studentVo);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/add")
    public ResponseVo<String> add(@RequestBody @Valid StudentAddDto dto) {
        try {
            Student student = _BeanUtil.copyProperties(dto, Student.class);
            studentService.saveAndCache(student);
            return ResponseVo.success(student.getId());
        } catch (Exception e) {
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/update")
    public ResponseVo<String> update(@RequestBody @Valid StudentUpdateDto dto) {
        try {
            Student student = _BeanUtil.copyProperties(dto, Student.class);
            studentService.updateByIdAndCache(student);
            return ResponseVo.success(student.getId());
        } catch (Exception e) {
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/delete")
    public ResponseVo delete(@RequestParam("id") String id){
        if (StrUtil.isBlank(id)) {
            return ResponseVo.fail("主键不能为空");
        }
        studentService.removeByIdAndCache(id);
        return ResponseVo.success();
    }

}

